package com.kugoweb.shthon2011s.tlwatch.settings;

import twitter4j.TwitterException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;

import com.kugoweb.shthon2011s.tlwatch.commons.TweetUtils;

public class OAuthTask extends AsyncTask<Void, Void, Void> {

	// private static final String TAG = OAuthTask.class.getSimpleName();

	public static final int ERROR_NETWORK = 1;
	public static final int ERROR_SERVER = 2;

	public interface OAuthTaskListener {
		void onBrowserCalled();

		void onFailure(int errorCode);
	}

	private final Activity mActivity;
	private final OAuthTaskListener mListener;

	private ProgressDialog mDialog;

	private Intent mAuthIntent = null;
	private Exception mException = null;

	public OAuthTask(final Activity activity, final OAuthTaskListener listener) {
		this.mActivity = activity;
		this.mListener = listener;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#onPreExecute()
	 */
	@Override
	protected void onPreExecute() {
		mDialog = new ProgressDialog(mActivity);
		mDialog.setCancelable(false);
		mDialog.show();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected Void doInBackground(final Void... params) {
		try {
			mAuthIntent = TweetUtils.getAuthIntent();
		} catch (final Exception e) {
			mException = e;
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(final Void result) {
		try {
			mDialog.dismiss();
		} catch (final Exception e) {
			// do nothing
		}
		if (mException == null) {
			mActivity.startActivity(mAuthIntent);
			mListener.onBrowserCalled();
		} else {
			if (mException instanceof TwitterException) {
				final TwitterException te = (TwitterException) mException;
				final int statusCode = te.getStatusCode();
				if (statusCode < 0) {
					mListener.onFailure(ERROR_NETWORK);
				} else {
					mListener.onFailure(ERROR_SERVER);
				}
			}
		}
	}

}
